//
//  HRNetworkManager.swift
//  微博
//
//  Created by 众力金融 on 2017/1/10.
//  Copyright © 2017年 众力金融. All rights reserved.
//

import UIKit
import AFNetworking

//swift 枚举支持任意类型
enum HRHTTPMethod {
    case GET
    case POST
}

//网络管理工具
class HRNetworkManager: AFHTTPSessionManager {

    //静态区 / 常量 / 闭包 / 在第一次访问时 执行闭包 并且将结果保存在shared常量中
    static let shared:HRNetworkManager = {
        
        let instance = HRNetworkManager()
        //设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //返回对象
        return instance
    }()
    
    //用户账户的懒加载属性
    lazy var userAccount = HRuserAccount()
    
    //访问令牌 所有网络请求 都基于此令牌(除登录除外)
    //访问的令牌有时限
    //模拟token过期
    //var accessToken: String? = "2.00Rb2WWGCVGTQD1c0c3766b8pJcJ2D"
    //var accessToken: String? = nil
    //用户id 5365823342
   // var uid: String? = "5365823342"
    
    var userlogon: Bool {
        return userAccount.access_token != nil
    }
    
    //专门负责拼接 token 的网络请求方法
    func tokenRequest(method:HRHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?,completion: @escaping (_ json: AnyObject, _ isScceed: Bool)->()) {
        
        //处理 token 字典
        //判断token 是否为 nil 如果为nil 直接返回 程序执行过程中 一般token 不会为nil
        guard let token = userAccount.access_token else {
             print("没有token 需要登录")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            //FIXME: 发送通知 提示用户登录
            completion("" as AnyObject, false)
            return
        }
       
        //判断参数字典是否存在 如果为nil 应该新创建个字典
        var parameters = parameters
        if parameters == nil {
            // 实例化字典
            parameters = [String: AnyObject]()
        }
        
        //设置参数字典
        parameters!["access_token"] = token as AnyObject
        
        //调用 request 发起真正的网络请求
        request(URLString: URLString, parameters: parameters, completion: completion)
    }
    
    /// Function types cannot have argument label 'json'; use '_' instead
    func request(method:HRHTTPMethod = .GET, URLString: String, parameters: [String: AnyObject]?,completion: @escaping (_ json: AnyObject, _ isScceed: Bool)->()) {
        
        // 成功回调
        let success = {(task: URLSessionDataTask,json: Any?) ->() in
            
             completion(json as AnyObject, true)
            
        }
        
        // 失败回调
        let failure = { (task: URLSessionDataTask?, error: Error)->() in
            
            //token 过期处理
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token 过期了")
                // 发送通知(本方法不知道被谁调用, 谁接受谁处理)
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "badtoken")
            }
            print("错误信息 \(error)")
                completion("" as AnyObject, true)
            }

        if method == .GET {
             get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
}
